<template>
  <main-header :show-search="false" />
  <el-container class="profile-layout">
    <el-main>
      <!-- Basic Info -->
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
            <router-link to="/">
              <el-button type="primary" plain>返回主页</el-button>
            </router-link>
          </div>
        </template>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="用户 ID">{{ user.id }}</el-descriptions-item>
          <el-descriptions-item label="昵称">{{ user.name }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ user.phoneNumber }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- Cart Info -->
      <el-card shadow="never" style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>购物车</span>
            <el-button v-if="cart.items.length > 0" type="danger" plain @click="handleClearCart">清空购物车</el-button>
          </div>
        </template>
        <el-table :data="cart.items" style="width: 100%" v-loading="cartStore.isLoading">
           <el-table-column label="商品" min-width="300">
            <template #default="scope">
              <router-link :to="`/product/${scope.row.productId}`" class="product-link">
                <el-image :src="scope.row.imageUrl" fit="cover" style="width: 60px; height: 60px; vertical-align: middle; margin-right: 10px;"></el-image>
                <span style="vertical-align: middle;">{{ scope.row.productName }}</span>
              </router-link>
            </template>
          </el-table-column>
          <el-table-column label="单价" width="120">
            <template #default="scope">
              <span>¥{{ scope.row.price.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="200">
            <template #default="scope">
              <el-input-number
                :model-value="scope.row.quantity"
                @change="(currentValue: number) => handleQuantityChange(scope.row.productId, currentValue)"
                :min="1"
                size="small"
                controls-position="right"
                style="width: 120px;"
              />
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120">
             <template #default="scope">
              <span>¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="danger" :icon="Delete" circle plain @click="handleRemoveItem(scope.row.productId)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="cart.items.length > 0" style="margin-top: 20px; text-align: right;">
          <strong>总金额: ¥{{ cart.totalAmount.toFixed(2) }}</strong>
        </div>
        <el-empty v-else description="购物车是空的" />
      </el-card>

      <!-- Addresses -->
      <el-card shadow="never" style="margin-top: 20px;">
        <template #header>
            <div class="card-header">
                <span>地址信息</span>
                <el-button type="primary" @click="handleOpenAddressDialog()">新增地址</el-button>
            </div>
        </template>
        <el-table :data="addresses" style="width: 100%">
          <el-table-column prop="id" label="地址 ID" width="80" />
          <el-table-column prop="receiverName" label="收件人" width="120" />
          <el-table-column prop="receiverPhone" label="联系电话" width="150" />
          <el-table-column label="地址详情">
            <template #default="scope">
              {{ formatAddressLine(scope.row) }}
            </template>
          </el-table-column>
           <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button size="small" @click="handleOpenAddressDialog(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDeleteAddress(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- Orders -->
      <el-card shadow="never" style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>订单信息</span>
            <el-switch
              v-model="showCompletedOrders"
              active-text="显示已完成订单"
            />
          </div>
        </template>
        <el-table :data="filteredOrders" style="width: 100%" v-loading="ordersLoading">
          <el-table-column label="商品名称" min-width="150">
            <template #default="scope">
              {{ scope.row.productName || 'N/A' }}
            </template>
          </el-table-column>
          <el-table-column label="收货地址" min-width="200">
            <template #default="scope">
              {{ scope.row.addressInfo || 'N/A' }}
            </template>
          </el-table-column>
          <el-table-column prop="totalAmount" label="总金额" width="100">
             <template #default="scope">
              ¥{{ scope.row.totalAmount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订单状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'end' ? 'success' : 'warning'">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="deliveryInfo.currentAddress" label="当前位置" min-width="150" />
          <el-table-column prop="deliveryInfo.delivererPhone" label="配送员电话" width="120" />
          <el-table-column label="下单日期" width="170">
            <template #default="scope">
              {{ formatDateToCN(scope.row.orderDate) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button
                v-if="scope.row.status !== 'end'"
                size="small"
                type="primary"
                @click="confirmReceipt(scope.row.id)"
              >
                确认收货
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

    </el-main>
  </el-container>

  <!-- Address Dialog -->
    <el-dialog v-model="addressDialogVisible" :title="addressDialogTitle" width="500px" @close="resetAddressForm">
        <el-form :model="formAddress" label-width="100px" ref="addressFormRef" :rules="addressRules">
            <el-form-item label="收件人" prop="receiverName">
                <el-input v-model="formAddress.receiverName" />
            </el-form-item>
            <el-form-item label="联系电话" prop="receiverPhone">
                <el-input v-model="formAddress.receiverPhone" />
            </el-form-item>
            <el-form-item label="国家" prop="country">
               <el-autocomplete
                  v-model="formAddress.country"
                  :fetch-suggestions="queryCountries"
                  placeholder="请输入国家"
                  style="width: 100%"
                  @select="handleCountryChange"
                  @change="handleCountryChange"
                />
            </el-form-item>
            <template v-if="isChina">
              <el-form-item label="省份" prop="province">
                  <el-autocomplete
                    v-model="formAddress.province"
                    :fetch-suggestions="queryProvinces"
                    placeholder="请输入省份"
                    style="width: 100%"
                    @select="handleProvinceSelect"
                  />
              </el-form-item>
              <el-form-item label="城市" prop="city">
                  <el-autocomplete
                    v-model="formAddress.city"
                    :fetch-suggestions="queryCities"
                    placeholder="请输入城市"
                    style="width: 100%"
                    @select="handleCitySelect"
                    :disabled="!formAddress.province || !selectedProvince"
                  />
              </el-form-item>
              <el-form-item label="地区/县" prop="county">
                  <el-autocomplete
                    v-model="formAddress.county"
                    :fetch-suggestions="queryCounties"
                    placeholder="请输入地区/县"
                    style="width: 100%"
                    :disabled="!formAddress.city || !selectedCity"
                  />
              </el-form-item>
            </template>
             <template v-else>
                <el-form-item label="省份" prop="province">
                    <el-input v-model="formAddress.province" />
                </el-form-item>
                <el-form-item label="城市" prop="city">
                    <el-input v-model="formAddress.city" />
                </el-form-item>
                <el-form-item label="地区/县" prop="county">
                    <el-input v-model="formAddress.county" />
                </el-form-item>
            </template>
            <el-form-item label="详细地址" prop="detailAddress">
                <el-input v-model="formAddress.detailAddress" type="textarea" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="addressDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitAddressForm">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue';
import { useRouter } from 'vue-router';
import apiClient from '../axios/axios';
import { useUserStore } from '../stores/user';
import { useCartStore } from '../stores/cart';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import MainHeader from '../components/MainHeader.vue';

interface User {
  id: number;
  name: string;
  phoneNumber: string;
}
interface Address {
  id: number;
  receiverName: string;
  receiverPhone: string;
  country: string;
  province: string;
  city: string;
  county: string;
  detailAddress: string;
}
type AddressForm = Omit<Address, 'id' | 'userId'>;

interface Order {
  id: number;
  customerId: number;
  productId: number;
  addressId: number;
  status: string;
  totalAmount: number;
  orderDate: string;
}

interface Deliver {
  id: number;
  orderId: number;
  addressId: number;
  currentAddress: string;
  delivererPhone: string;
}

interface Product { id: number; name: string; }

interface EnhancedOrder extends Order {
  productName?: string;
  addressInfo?: string;
  deliveryInfo?: Deliver;
}

const formatAddressLine = (address: Address) => {
  return [address.country, address.province, address.city, address.county, address.detailAddress].filter(Boolean).join(' ');
}

const userStore = useUserStore();
const cartStore = useCartStore();
const router = useRouter();

const user = ref<User>({ id: 0, name: '', phoneNumber: '' });
const addresses = ref<Address[]>([]);
const loading = ref(false);
const countries = ref<{ value: string }[]>([]);
const chinaRegions = ref<any[]>([]);
const chinaRegionsLoading = ref(true);

const cart = computed(() => cartStore.cart);

const isChina = computed(() => {
  const val = formAddress.country?.toLowerCase() || '';
  return val.includes('china') || formAddress.country.includes('中国');
});

const fetchGeoData = async () => {
  try {
    const [countriesRes, chinaRes] = await Promise.all([
      fetch('https://restcountries.com/v3.1/all?fields=name,translations'),
      fetch('https://cdn.jsdelivr.net/gh/modood/Administrative-divisions-of-China@master/dist/pca-code.json')
    ]);
    const countriesData = await countriesRes.json();
    countries.value = countriesData.map((c: any) => {
      let display = c.translations?.zho?.common || c.name.common;
      if (display === 'China') display = '中国';
      return { value: display };
    }).sort((a: { value: string }, b: { value: string }) => a.value.localeCompare(b.value));
    chinaRegions.value = (await chinaRes.json()) || [];
    chinaRegionsLoading.value = false;
  } catch (error) {
    console.error("Failed to fetch geo data", error);
    ElMessage.error("地理位置数据加载失败");
    chinaRegionsLoading.value = false;
  }
};

const fetchAllData = async () => {
  if (!userStore.user) {
    ElMessage.warning('请先登录');
    router.push('/');
    return;
  }
  loading.value = true;
  try {
    const [userRes, cartRes, addrRes] = await Promise.all([
      apiClient.get<User>(`/user/${userStore.user.id}`),
      cartStore.getCart(), // This is a method from the store
      apiClient.get<Address[]>(`/address/user/${userStore.user.id}`),
    ]);
    user.value = userRes.data;
    addresses.value = addrRes.data;
  } catch (e) {
    console.error(e);
    ElMessage.error('加载个人信息失败');
  } finally {
    loading.value = false;
  }
};

const handleQuantityChange = (productId: number, quantity: number) => {
  if (quantity > 0) {
    cartStore.updateItemQuantity(productId, quantity);
  }
};

const handleRemoveItem = (productId: number) => {
  cartStore.removeItem(productId);
};

const handleClearCart = async () => {
    await ElMessageBox.confirm('确定要清空购物车中的所有商品吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    });
    await cartStore.clearCart();
};

// --- Address Management ---
const addressDialogVisible = ref(false);
const addressDialogTitle = ref('');
const addressFormRef = ref<FormInstance>();
const editingAddressId = ref<number | null>(null);

const initialFormAddressState: AddressForm = {
    receiverName: '',
    receiverPhone: '',
    country: '',
    province: '',
    city: '',
    county: '',
    detailAddress: '',
};
const formAddress = reactive({ ...initialFormAddressState });

const addressRules = reactive<FormRules>({
    receiverName: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' }],
    receiverPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
    country: [{ required: true, message: '请输入国家', trigger: 'blur' }],
    province: [{ required: true, message: '请输入省份', trigger: 'blur' }],
    city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
    county: [{ required: true, message: '请输入地区/县', trigger: 'blur' }],
    detailAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
});

const selectedProvince = ref<any>(null);
const selectedCity = ref<any>(null);

const resetAddressForm = () => {
  Object.assign(formAddress, initialFormAddressState);
  editingAddressId.value = null;
  selectedProvince.value = null;
  selectedCity.value = null;
  addressFormRef.value?.clearValidate();
};

const handleOpenAddressDialog = (address?: Address) => {
  if (address) {
    addressDialogTitle.value = '编辑地址';
    editingAddressId.value = address.id;
    const { id, ...formData } = address;
    Object.assign(formAddress, formData);
  } else {
    addressDialogTitle.value = '新增地址';
    resetAddressForm();
    formAddress.country = '中国';
  }
  addressDialogVisible.value = true;
};

const queryCountries = (queryString: string, cb: (arg: any) => void) => {
  const results = queryString
    ? countries.value.filter(c => c.value.toLowerCase().includes(queryString.toLowerCase()))
    : countries.value;
  cb(results);
};

const handleCountryChange = () => {
  formAddress.province = '';
  formAddress.city = '';
  formAddress.county = '';
  selectedProvince.value = null;
  selectedCity.value = null;
};

const queryProvinces = (queryString: string, cb: (arg: any) => void) => {
  if (!isChina.value || chinaRegionsLoading.value || !chinaRegions.value.length) {
    cb([]);
    return;
  }
  const results = chinaRegions.value
    .map((p: any) => ({ value: p.name, data: p }))
    .filter((p: any) => p.value.toLowerCase().includes(queryString.toLowerCase()));
  cb(results);
};

const handleProvinceSelect = (item: { value: string, data: any }) => {
  formAddress.province = item.value;
  selectedProvince.value = item.data;
  formAddress.city = '';
  formAddress.county = '';
  selectedCity.value = null;
};

const queryCities = (queryString: string, cb: (arg: any) => void) => {
  if (!selectedProvince.value?.children || chinaRegionsLoading.value) {
    cb([]);
    return;
  }
  const results = selectedProvince.value.children
    .map((c: any) => ({ value: c.name, data: c }))
    .filter((c: any) => c.value.toLowerCase().includes(queryString.toLowerCase()));
  cb(results);
};

const handleCitySelect = (item: { value: string, data: any }) => {
  formAddress.city = item.value;
  selectedCity.value = item.data;
  formAddress.county = '';
};

const queryCounties = (queryString: string, cb: (arg: any) => void) => {
  if (!selectedCity.value?.children || chinaRegionsLoading.value) {
    cb([]);
    return;
  }
  const results = selectedCity.value.children
    .map((c: any) => ({ value: c.name, data: c }))
    .filter((c: any) => c.value.toLowerCase().includes(queryString.toLowerCase()));
  cb(results);
};

const submitAddressForm = async () => {
  if (!addressFormRef.value) return;
  await addressFormRef.value.validate(async (valid) => {
    if (valid) {
      const payload = { ...formAddress, userId: userStore.user!.id };
      try {
        if (editingAddressId.value) {
          await apiClient.put(`/address/${editingAddressId.value}`, payload);
          ElMessage.success('地址更新成功');
        } else {
          await apiClient.post('/address', payload);
          ElMessage.success('地址添加成功');
        }
        addressDialogVisible.value = false;
        await fetchAllData(); // Refresh all data
      } catch (error) {
        ElMessage.error('操作失败');
      }
    }
  });
};

const handleDeleteAddress = async (addressId: number) => {
    try {
        await ElMessageBox.confirm('确定要删除这个地址吗?', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        });
        await apiClient.delete(`/address/${addressId}`);
        ElMessage.success('地址删除成功');
        await fetchAllData(); // Refresh all data
    } catch (error) {
        // If user clicks cancel, an error is thrown, which we can ignore
        if (error !== 'cancel') {
          ElMessage.error('删除失败');
        }
    }
};

const ordersLoading = ref(false);
const showCompletedOrders = ref(false);

const enhancedOrders = ref<EnhancedOrder[]>([]);

const filteredOrders = computed(() => {
  if (showCompletedOrders.value) {
    return enhancedOrders.value;
  }
  return enhancedOrders.value.filter(order => order.status !== 'end');
});

const fetchOrders = async () => {
  if (!user.value?.id) return;
  ordersLoading.value = true;
  try {
    const [ordersRes, productsRes, addressesRes, deliversRes] = await Promise.all([
      apiClient.get<Order[]>(`/orders/user/${user.value.id}`),
      apiClient.get<Product[]>('/product'),
      apiClient.get<Address[]>(`/address/user/${user.value.id}`),
      apiClient.get<Deliver[]>('/delivers')
    ]);

    const productMap = new Map(productsRes.data.map(p => [p.id, p.name]));
    const addressMap = new Map(addressesRes.data.map(a => [a.id, formatAddressLine(a)]));
    const deliveryMap = new Map(deliversRes.data.map(d => [d.orderId, d]));

    enhancedOrders.value = ordersRes.data.map(order => ({
      ...order,
      productName: productMap.get(order.productId),
      addressInfo: addressMap.get(order.addressId),
      deliveryInfo: deliveryMap.get(order.id)
    }));
    
  } catch (error) {
    console.error("Failed to fetch orders or related data", error);
    ElMessage.error('获取订单信息失败');
  } finally {
    ordersLoading.value = false;
  }
};

const confirmReceipt = async (orderId: number) => {
  try {
    await apiClient.put(`/orders/${orderId}`, { status: 'end' });
    ElMessage.success('操作成功，订单已完成');
    // Refresh the specific order in the list
    const order = enhancedOrders.value.find(o => o.id === orderId);
    if (order) {
      order.status = 'end';
    }
  } catch (error) {
    console.error('Failed to confirm receipt', error);
    ElMessage.error('确认收货失败');
  }
};

const formatDateToCN = (iso: string) => {
  if (!iso) return '';
  const date = new Date(iso);
  // 转换到中国时区并格式化 YYYY-MM-DD HH:mm:ss
  return date.toLocaleString('zh-CN', {
    hour12: false,
    timeZone: 'Asia/Shanghai',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
};

onMounted(async () => {
  if (userStore.isLoggedIn) {
    await fetchAllData(); 
    await fetchOrders();
    await cartStore.getCart();
  } else {
    router.push('/');
  }
});
</script>

<style scoped>
.profile-layout {
  padding: 20px;
  background-color: #f5f7fa;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.product-link {
  color: inherit;
  text-decoration: none;
  display: flex;
  align-items: center;
}
.product-link:hover {
  color: #409eff;
}
</style> 